package com.Policing.Receive;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.Policing.Adapter.Input_Adapter_item;
import com.Policing.Adapter.MyAdapter;
import com.Policing.Ip_set.Ip_Set;
import com.Policing.R;
import com.Policing.Scan.qrcode.util.Constant;
import com.Policing.Scan.zxing.activity.CaptureActivity;
import com.Policing.bean.Input_item;
import com.Policing.bean.Issued_bean;
import com.Policing.bean.Receive_out_bean;
import com.Policing.misc.Accompaniment;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hb.dialog.dialog.LoadingDialog;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2019/1/10.
 */

public class Receive_out extends Activity {
    private ListView applying;
    private String rfid_url="http://"+ Ip_Set.IP+"/api/receivesPutRFID";
    private final Accompaniment accompaniment = Accompaniment.newInstanceOfResource(this, R.raw.tag_inventoried);
    //播放声音
    private ListView encoding;//扫码
    private TextView et_out;//扫码
    LoadingDialog loadingDialog;
    private List list = new ArrayList(){};
    private String coding_name;//资产编号
    private String url;
    private ImageView scan_img;
    private ImageView fh;
    private TextView title_text;
    List<Map<String, Object>> encoding_list = new ArrayList<Map<String, Object>>();
    private Handler accompainimentsHandler;
    private boolean state;
    private boolean stop_rfid =true;
    private List<Input_item> data = new ArrayList<>();
    private final Runnable accompainimentRunnable = new Runnable() {
        @Override
        public void run() {
            accompaniment.start();
            accompainimentsHandler.removeCallbacks(this);
        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.receive_out);
        HandlerThread htHandlerThread = new HandlerThread("");
        htHandlerThread.start();
        accompainimentsHandler = new Handler(htHandlerThread.getLooper());
        url="http://"+ Ip_Set.IP+"/api/receivesPut";
        inview();


    }

    private void inview() {
        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("发放");
        fh = (ImageView) findViewById(R.id.fh);
        fh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        scan_img = (ImageView) findViewById(R.id.scan_img);

        applying = (ListView) findViewById(R.id.applying);
        encoding = (ListView) findViewById(R.id.encoding);
        et_out = (TextView) findViewById(R.id.receive_out_et);
         Intent in = getIntent();
        coding_name = in.getExtras().getString("coding_name");
        load(coding_name,"");
        scan_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQrCode();
            }
        });

    }


    private void load(final String receivesId, final String assetNumber) {

        new Thread(){
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("receivesId",receivesId)
                            .add("assetNumber",assetNumber)
                            .build();
                    Request request = new Request.Builder()
                            .url(url)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.i("222",responseData);
                    if (assetNumber.equals("")){
                        showResponse(responseData);//解析
                    }else if (!assetNumber.equals("")){
                        showResponse_o(responseData);//解析
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }.start();
    }

    private void showResponse_o(final String responseData) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                JSONObject json = null;
                Bitmap bitmap =null;
                try {
                    json = new JSONObject(responseData);
                    if (json.getString("state").equals("0"))
                    {
                Toast.makeText(Receive_out.this,"失败",Toast.LENGTH_SHORT).show();

                    }
                    if (json.getString("state").equals("1"))
                    {
                        Toast.makeText(Receive_out.this,"资产不存在",Toast.LENGTH_SHORT).show();

                    }
                    if (json.getString("state").equals("8"))
                    {
                        Toast.makeText(Receive_out.this,"资产被占用",Toast.LENGTH_SHORT).show();

                    }
                    if (json.getString("state").equals("2"))
                    {
                        Toast.makeText(Receive_out.this,"重复发放",Toast.LENGTH_SHORT).show();

                    }
                    if (json.getString("state").equals("3"))
                    {

                        Toast.makeText(Receive_out.this,"资产未入库或被占用",Toast.LENGTH_SHORT).show();

                    }
                    if (json.getString("state").equals("4"))
                    {
                        Toast.makeText(Receive_out.this,"未申请此类型的资产",Toast.LENGTH_SHORT).show();


                    }
                    if (json.getString("state").equals("5"))
                    {
                        Toast.makeText(Receive_out.this,"此类型资产发放完全",Toast.LENGTH_SHORT).show();

                    }
                    if (json.getString("state").equals("6"))
                    {
                        load(coding_name,"");
                        Toast.makeText(Receive_out.this,"全部发放完全",Toast.LENGTH_SHORT).show();
                        finish();
                    }
                    if (json.getString("state").equals("7"))
                    {
                        load(coding_name,"");
                        Toast.makeText(Receive_out.this,"发放成功",Toast.LENGTH_SHORT).show();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void showResponse(final String responseData) {
      runOnUiThread(new Runnable() {
          @Override
          public void run() {
              list.clear();
              data.clear();
              Bitmap bitmap =null;
              JSONObject jsonObject =null;
              JSONArray json =null;
              JSONArray assets = null;
              try {
                  jsonObject = new JSONObject(responseData);
                   json = jsonObject.getJSONArray("ss");
                  assets = jsonObject.getJSONArray("assets");
              } catch (JSONException e) {
                  e.printStackTrace();
              }
              Gson gson = new Gson();
              List<Receive_out_bean> userList1 = gson.fromJson(String.valueOf(json), new TypeToken<List<Receive_out_bean>>(){}.getType());
              for(int i = 0;i < userList1.size();i++){
                  list.add(userList1.get(i).getType());
              }
              applying.setAdapter(new ArrayAdapter<String>(Receive_out.this,
                      android.R.layout.simple_list_item_1, list));
              List<Issued_bean> userList = gson.fromJson(String.valueOf(assets), new TypeToken<List<Issued_bean>>(){}.getType());
              for(int i = 0;i < userList.size();i++){
                  String assetName = userList.get(i).getAssetName();
                  String deptId = userList.get(i).getDeptId();
                  String assetNumber =userList.get(i).getAssetNumber();
                  String userId = userList.get(i).getUserId();
                  String model = userList.get(i).getModel();
                  String type = userList.get(i).getType();
                  if (userList.get(i).getImage().equals("")){// wh getResources().openRawResource(R.mipmap.null_po);
                      @SuppressLint("ResourceType") InputStream is = getResources().openRawResource(R.mipmap.null_po);
                      bitmap = BitmapFactory.decodeStream(is);
                  }else {
                      byte [] input = Base64.decode(userList.get(i).getImage(), Base64.DEFAULT);
                      bitmap = BitmapFactory.decodeByteArray(input, 0, input.length);
                  }
                  data.add(new Input_item(bitmap,assetName,deptId,assetNumber,userId,model,type,""));

              }
              Input_Adapter_item adapter_item = new Input_Adapter_item(Receive_out.this,R.layout.input_adapter_item,data);
              encoding.setAdapter(adapter_item);
          }
      });

    }
    @Override
    protected void onDestroy() {
        if (accompainimentsHandler != null) {
            accompainimentsHandler.getLooper().quit();
        }
        accompaniment.release();
        stop_rfid=false;
        super.onDestroy();
    }
    private void trigTagAccompainiment() {
        accompainimentsHandler.post(accompainimentRunnable);
    }
    private void updata(final String rfid_data){
        new Thread(){
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("rfid",rfid_data)
                            .add("receivesId",coding_name)
                            .build();
                    Request request = new Request.Builder()
                            .url(rfid_url)
                            .post(requestBody).build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    Log.i("222",responseData);
                    rfid_showResponse(responseData);//解析
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }.start();

    }

    private void rfid_showResponse(final String responseData) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                JSONObject json = null;
                try {
                    json = new JSONObject(responseData);
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("coding", json.getString("assetName"));
                    map.put("coding_num",json.getString("assetNumber"));
                    map.put("coding_sate", json.getString("state"));
                    Collections.reverse(encoding_list);
                    encoding_list.add(map);
                    Collections.reverse(encoding_list);
                    MyAdapter myAdapter = new MyAdapter(Receive_out.this, encoding_list);
                    //设置适配器
                    encoding.setAdapter(myAdapter);
                    load(coding_name,"");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
    // 开始扫码
    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(Receive_out.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Receive_out.this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(Receive_out.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Receive_out.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(Receive_out.this, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Receive_out.this, "请至权限中心打开本应用的相机访问权限", Toast.LENGTH_LONG).show();
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    Toast.makeText(Receive_out.this, "请至权限中心打开本应用的文件读写权限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
            et_out.setText(scanResult);
            load(coding_name,scanResult);
        }
    }
}
